/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
 */

package com.example.daxiguaforharmony.utils;


import ohos.agp.components.Image;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.global.resource.Resource;
import ohos.global.resource.ResourceManager;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Rect;
import ohos.media.image.common.Size;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

public class Utils {
    private static final String TAG = Utils.class.getSimpleName();

    private static Map<Integer, PixelMap> imageCacheForMultimedia = new HashMap<>();

    private static Map<Integer, PixelMap> imageCacheForCamera = new HashMap<>();

    private Utils() {
    }

    /**
     * set image
     *
     * @param context context
     * @param image image
     * @param resourceId resource id
     * @param isCamera isCameraPage
     */
    public static void setImage(Context context, Image image, int resourceId, boolean isCamera) {
        if (context == null || image == null) {
            LogUtil.error(TAG, "setImage but slice or image is null");
            return;
        }
        try {
            PixelMap pixelMap = createByResourceId(context, resourceId, "image/png", isCamera);
            image.setPixelMap(pixelMap);
        } catch (IOException | NotExistException e) {
            LogUtil.error(TAG, "setImage " + e.getLocalizedMessage());
        }
    }

    /**
     * create pixel map by resource id
     *
     * @param context context
     * @param resourceId resource id
     * @param formatHint format hint
     * @param isCamera isCamera
     * @return PixelMap pixel map
     * @throws IOException io
     * @throws NotExistException not exist
     */
    public static PixelMap createByResourceId(Context context, int resourceId, String formatHint, boolean isCamera)
        throws IOException, NotExistException {
        if (context == null) {
            LogUtil.error(TAG, "createByResourceId but slice is null");
            throw new IOException();
        }
        if (isCamera) {
            // cache first
            if (imageCacheForCamera.containsKey(resourceId)) {
                return imageCacheForCamera.get(resourceId);
            }
        } else {
            // cache first
            if (imageCacheForMultimedia.containsKey(resourceId)) {
                return imageCacheForMultimedia.get(resourceId);
            }
        }

        ResourceManager manager = context.getResourceManager();
        if (manager == null) {
            LogUtil.error(TAG, "get resource manager failed");
            throw new IOException();
        }
        Resource resource = manager.getResource(resourceId);
        if (resource == null) {
            throw new IOException();
        }
        ImageSource.SourceOptions srcOpts = new ImageSource.SourceOptions();
        srcOpts.formatHint = formatHint;

        ImageSource imageSource = null;
        try {
            imageSource = ImageSource.create(readResource(resource), srcOpts);
        } finally {
            close(resource);
        }
        if (imageSource == null) {
            LogUtil.error(TAG, "imageSource is null");
            throw new FileNotFoundException();
        }
        ImageSource.DecodingOptions decodingOpts = new ImageSource.DecodingOptions();
        decodingOpts.desiredSize = new Size(0, 0);
        decodingOpts.desiredRegion = new Rect(0, 0, 0, 0);
        decodingOpts.desiredPixelFormat = PixelFormat.ARGB_8888;

        PixelMap pixelmap = imageSource.createPixelmap(decodingOpts);
        if (isCamera) {
            imageCacheForCamera.put(resourceId, pixelmap);
        } else {
            imageCacheForMultimedia.put(resourceId, pixelmap);
        }
        return pixelmap;
    }

    public static byte[] readResource(Resource resource) {
        final int bufferSize = 1024;
        final int ioEnd = -1;

        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[bufferSize];
        while (true) {
            try {
                int readLen = resource.read(buffer, 0, bufferSize);
                if (readLen == ioEnd) {
                    LogUtil.debug(TAG, "readResource finish");
                    break;
                }
                output.write(buffer, 0, readLen);
            } catch (IOException e) {
                LogUtil.error(TAG, "readResource failed " + e.getLocalizedMessage());
                break;
            }
        }
        LogUtil.debug(TAG, "readResource len: " + output.size());
        return output.toByteArray();
    }

    private static void close(Resource resource) {
        if (resource != null) {
            try {
                resource.close();
            } catch (IOException e) {
                LogUtil.error(TAG, "close resource error");
            }
        }
    }

    /**
     * release PixelMap, call before multimedia aAbility exit
     */
    public static void releasePixelMap() {
        LogUtil.debug(TAG, "releasePixelMap begin");
        for (Map.Entry<Integer, PixelMap> entry : imageCacheForMultimedia.entrySet()) {
            if (entry.getValue() != null) {
                entry.getValue().release();
            }
        }
        imageCacheForMultimedia.clear();
        LogUtil.debug(TAG, "releasePixelMap end");
    }

    /**
     * release PixelMap, call before camera aAbility exit
     */
    public static void releasePixelMapForCamera() {
        LogUtil.debug(TAG, "releasePixelMapForCamera begin");
        for (Map.Entry<Integer, PixelMap> entry : imageCacheForCamera.entrySet()) {
            if (entry.getValue() != null) {
                entry.getValue().release();
            }
        }
        imageCacheForCamera.clear();
        LogUtil.debug(TAG, "releasePixelMapForCamera end");
    }
    /**方法二：推荐，速度最快
     * 判断是否为整数
     * @param str 传入的字符串
     * @return 是整数返回true,否则返回false
     */
    public static boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }
}
